//
//  EBHeader.m
//  UMDReader
//
//  Created by 张 霄鹤 on 10-2-1.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "EBHeader.h"
#import "BEDataInputStream.h"


@implementation EBHeader

@synthesize title;
@synthesize author;
@synthesize vendor;
@synthesize buyer;

- (id)init{
	if(self = [super init]){
		title = @"无标题";
		author = @"vhly[FR]";
		vendor = @"FR";
		NSDate *d = [[NSDate alloc] init];
		createTime = [d timeIntervalSince1970];
		[d release];
		category = @"自创天书";
		buyer = @"vhly@163.com";
		
		titles = [[NSMutableArray alloc] init];
		offsets = [[NSMutableArray alloc] init];
		
		char key[] = {93,24,6,7,43,23,15,88,99,22,11,32,45,4,2,56,'\0'};
		pass = key;
	}
	return self;
}

- (void)load:(char *)buf length:(NSInteger)rlen needCrypt:(BOOL)crypted{
	if(crypted){
		[self cryptHeader:buf length:rlen];
	}
	NSData *d = [[NSData alloc] initWithBytes:buf length:rlen]; //dataWithBytes:buf length:rlen];
	BEDataInputStream *din = [[BEDataInputStream alloc] initWithData:d];
	version = [din read];
	bookType = [din read];
	NSInteger cl = [din readInt];
	if(cl > 0){
		NSInteger trlen = 0;
		char *data = [din getCurrentBytesRefwithLength:cl retLength:&trlen];
		NSData *d1 = [NSData dataWithBytes:data length:trlen];
		cover = [UIImage imageWithData:d1];
	}
	title = [din readUTF];
	author = [din readUTF];
	vendor = [din readUTF];
	createTime = [din readLong];
	category = [din readUTF];
	buyer = [din readUTF];
	NSInteger count = [din readInt];
	NSString *t;
	int off;
	for (int i = 0; i<count; i++) {
		t = [din readUTF];
		off = [din readInt];
		[titles addObject:t];
		[offsets addObject:[NSString stringWithFormat:@"%d",off]];
	}
	[din release];
	[d release];
}

- (void)cryptHeader:(char *)buf length:(NSInteger)rlen{
	int len1 = strlen(pass);
	int len2 = rlen;
	for(int i = 0, j = 0;i<len2;i++){
		if(j == len1){
			j = 0;
		}
		buf[i] ^= pass[j];
		j++;
	}
}

- (NSArray *)getTitles{
	return titles;
}

- (NSArray *)getOffsets{
	return offsets;
}

- (void)dealloc{
	[title release];
	[author release];
	[vendor release];
	[category release];
	[buyer release];
	
	[titles release];
	[offsets release];
	
	[super dealloc];
}

@end
